package com.system.orderserver.service.impl;

import com.system.commonutils.utils.RandomUtils;
import com.system.orderserver.mapper.*;
import com.system.orderserver.pojo.*;
import com.system.orderserver.result.*;
import com.system.orderserver.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired(required = false)
    private OrdersMapper ordersMapper;
    @Autowired(required = false)
    private OrdersInfoMapper ordersInfoMapper;
    @Autowired(required = false)
    private GoodsMapper goodsMapper;
    @Autowired(required = false)
    private ExceptionOrdersMapper exceptionOrdersMapper;
     @Autowired(required = false)
    private UserMapper userMapper;


    @Override
    public OrdersInfo_Result selectOrderInfo(Integer orderId) {
        System.out.println(orderId);
        //根据订单ID查询订单相关信息
        OrderResult orderResult = ordersMapper.selectOrderInfo(orderId);
        if(orderResult !=null && orderResult.getUserId()!=null){
            //根据用户ID查询用户相关信息
            UserInfoResult userInfoResult = userMapper.selectUserInfo(orderResult.getUserId());
            //根据订单ID查询商品ID、商品规格ID
            List<OrdersInfo> listGoods = ordersInfoMapper.selectGoodsId(orderId);

            List<Map<Integer ,Integer>> listmap= new ArrayList<>();//定义集合 存放商品ID和规格ID
            for (OrdersInfo goods:listGoods
            ) {
                Map<Integer,Integer> map = new HashMap<Integer,Integer>();
                map.put(goods.getOrdersinfoGoodsid(),goods.getSpecificationsId());
                listmap.add(map);
            }
            for (Map<Integer,Integer> map:listmap){
                Set<Integer> keyset = map.keySet();
                for (Integer key:keyset
                ) {
                    System.out.println(key+"value:"+map.get(key));
                }
            }
            //根据商品ID和规格ID查询商品详细信息
            List<GoodsResult>  goodsResult = goodsMapper.selectGoodsInfo(listmap);
            double ddyje = 0;//订单原金额
            double ddxje=0;//订单现金额
            double ddyf=0;//订单运费
            for (GoodsResult goods:goodsResult
            ) {
                ddyje=ddyje+(goods.getGoodsOldprice()+goods.getGoodsFreight())*goods.getGoodsNumber();
                ddxje=ddxje+( goods.getGoodsNewprice()+goods.getGoodsFreight())*goods.getGoodsNumber();
                ddyf=ddyf+goods.getGoodsFreight()*goods.getGoodsNumber();
            }
            if(orderResult.getCouponMoney()!=null){
                ddxje=ddxje-orderResult.getCouponMoney();//订单现金额-优惠券金额
            }
            System.out.println("订单原金额："+ddyje);
            System.out.println("订单现金额："+ddxje);
            System.out.println("运费："+ddyf);
            OrdersInfo_Result ordersInfo_result =    new OrdersInfo_Result();
            ordersInfo_result.setOrdersId(orderResult.getOrdersId());
            ordersInfo_result.setOrdersNo(orderResult.getOrdersNo());
            ordersInfo_result.setUserinfoNickname(userInfoResult.getUsername());
            ordersInfo_result.setOrdersCreatetime(orderResult.getOrdersCreatetime());
            ordersInfo_result.setAccountId(userInfoResult.getAccountId());
            ordersInfo_result.setList(goodsResult);
            ordersInfo_result.setOrdersOldprice(ddyje);
            ordersInfo_result.setFreight(ddyf);
            ordersInfo_result.setCouponMoney(orderResult.getCouponMoney());
            ordersInfo_result.setCouponStartMoney(orderResult.getCouponStartMoney());
            ordersInfo_result.setOrdersMoney(ddxje);
            ordersInfo_result.setUserAddressProvince(userInfoResult.getUserAddressProvince());
            ordersInfo_result.setUserAddressCity(userInfoResult.getUserAddressCity());
            ordersInfo_result.setUserAddressArea(userInfoResult.getUserAddressArea());
            ordersInfo_result.setUserAddressDetail(userInfoResult.getUserAddressDetail());
            ordersInfo_result.setPhone(userInfoResult.getPhone());
            ordersInfo_result.setLogisticsName(orderResult.getLogisticsName());
            ordersInfo_result.setPaymentMethod(orderResult.getPaymentmethod());
            ordersInfo_result.setOrdersState(orderResult.getOrdersState());
            ordersInfo_result.setLogisticsNo(orderResult.getLogisticsNo());
            return ordersInfo_result;
        }
        return null;
    }

    @Override
    @Transactional
    public String deleteOrder(Integer orderId) {
        //删除订单表记录
        ordersMapper.deleteOrder(orderId);
        //删除订单详情表记录
        Integer row = ordersInfoMapper.deleteOrderInfo(orderId);
        return row>0?"成功":"失败";
    }

    @Override
    public List<OrdersList_Result> selectOrders(Integer page,Integer limit,String orderNo, Integer ordersState, String startTiem, String endTiem) {
        Date starttime = str_Date(startTiem);
        Date endtiem=str_Date(endTiem);
        //查询订单相关信息
        return  ordersMapper.selectOrders((page-1)*limit,limit,orderNo,ordersState,starttime,endtiem);
    }

    @Override
    public Integer countOrder(String orderNo, Integer ordersState, String startTiem, String endTiem) {
        Date starttime = str_Date(startTiem);
        Date endtiem=str_Date(endTiem);
        return ordersMapper.countOrder(orderNo,ordersState,starttime,endtiem);
    }
    //将字符串转换成date类型
    private  Date str_Date(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date datetime = null;
        if (date != null && !date.equals("")) {
            try {
                datetime = sdf.parse(date);
                return datetime;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    @Transactional
    public String addOrder(Integer userId, Integer couponId, Integer ordersState, Integer harvestType,
                           Integer paymentMethod, Integer logisticsId, Integer selfAddressId,
                           Integer userAddressId, String goodsId, String goodsNumber, String specificationsId) {
        String[] goodsIdArr=goodsId.split(",");
        String[] goodsNumberArr=goodsNumber.split(",");
        String[] specificationsIdArr=specificationsId.split(",");
        System.out.println("商品id："+goodsId+"商品数量："+goodsNumber+"商品规格id："+specificationsId);
        Double goodsMoney = 0.0;
        if(goodsIdArr!=null &&goodsIdArr.length>0){
            //根据商品id查询商品价格和运费的和
            List<Double> goodsPrice = ordersMapper.goodsPrice(goodsIdArr);
            for (int i=0;i<goodsIdArr.length;i++){
                goodsMoney=goodsMoney+goodsPrice.get(i)*Integer.parseInt(goodsNumberArr[i]);
        }

        }
        Double youHuiJinE = 0.0;
        if(couponId !=null && couponId!=0){
            //根据id查询优惠券优惠金额
            youHuiJinE = ordersMapper.selectYouHuiJinE(couponId);
        }
        System.out.println(goodsMoney+":"+(goodsMoney-youHuiJinE));

       Orders order = new Orders();
        order.setOrdersNo(RandomUtils.createOrderId());
        order.setOrdersCreatetime(new Date());
        order.setUserId(userId);
        order.setCouponId(couponId);
        order.setOrdersState(ordersState);
        order.setOrdersTotleprice(youHuiJinE);
        order.setHarvesttype(harvestType);
        order.setPaymentmethod(paymentMethod);
        order.setSelfaddressid(selfAddressId);
        order.setUseraddressid(userAddressId);
        if(harvestType==1){//收货类型 1、配送上门 2、自取
            ordersMapper.addOrder01(order);
        }else{
            ordersMapper.addOrder02(order);
        }
        ArrayList<Integer> goodsIdList= new ArrayList<>();
        ArrayList<Integer> goodsNumberList= new ArrayList<>();
        ArrayList<Integer> specificationsIdList= new ArrayList<>();

        ArrayList<OrdersInfo> orderInfoList=new ArrayList<>();
        for(int i=0;i<goodsIdArr.length;i++){
            OrdersInfo ordersInfo  = new OrdersInfo();
            ordersInfo.setOrdersinfoOrderid(order.getOrdersId());
            ordersInfo.setOrdersinfoGoodsid(Integer.parseInt(goodsIdArr[i]));
            ordersInfo.setGoodsNumber(Integer.parseInt(goodsNumberArr[i]));
            ordersInfo.setSpecificationsId(Integer.parseInt(specificationsIdArr[i]));
            orderInfoList.add(ordersInfo);
        }
        System.out.println(order.getOrdersId());
        Integer row = ordersMapper.addOrderInfo(orderInfoList);
        return row>0?"成功":"失败";
    }

    @Override
    public List<NotDeliveredOrdersResult> selectNotDeliveredOrders(Integer page, Integer limit) {
        //查询未发货订单相关信息
        List<NotDeliveredOrdersResult> list = ordersMapper.selectNotDeliveredOrder((page-1)*limit,limit);
        return list;
    }

    @Override
    public Integer selectNotDeliveredOrdersCount() {
        return ordersMapper.selectNotDeliveredOrdersCount();
    }

    @Override
    @Transactional
    public String deliverGoods(Integer orderId,String logisticsNo) {
        ordersMapper.addLogisticsNo(logisticsNo,orderId);//订单添加物流单号
        return ordersMapper.deliverGoods(orderId)>0?"成功":"失败";
    }

    @Override
    public List<ExceptionOrder_Result> selectExceptionOrder(Integer page, Integer limit, Integer orderId,
                                          String startTime, String endTime, String userName, Integer exceptionOrdersSpeed) {
        Date starttime = str_Date(startTime);
        Date endtime = str_Date(endTime);
        return ordersMapper.selectExceptionOrder((page-1)*limit,limit,orderId,starttime,endtime,userName,exceptionOrdersSpeed);

    }

    @Override
    public Integer countExceptionOrder(Integer orderId, String startTime, String endTime, String userName, Integer exceptionOrdersSpeed) {
        return ordersMapper.countExceptionOrder(orderId,startTime,endTime,userName,exceptionOrdersSpeed);
    }

    @Override
    @Transactional
    public String returnGoods(Integer orderId,Integer state) {//退货、换货、取消订单
        ExceptionOrders exceptionOrders =exceptionOrdersMapper.selectByIdExceptionOrders(orderId);
        if(exceptionOrders != null && exceptionOrders.getOrdersId()!=null){
            if(state==1){
                return "订单已申请退货，请勿重复操作";
            }else if(state==2){
                return "订单已申请换货，请勿重复操作";
            }else if(state==3){
                return "订单已申请取消交易，请勿重复操作";
            }
        }else{
            ordersMapper.updateOrder(orderId);//将订单状态改为异常状态
            ExceptionOrders exceptionOrder = new ExceptionOrders();
            exceptionOrder.setOrdersId(orderId);
            exceptionOrder.setCreatetime(new Date());
            exceptionOrder.setExceptionordersState(state);
            exceptionOrder.setExceptionordersSpeed(1);
            Integer row  = ordersMapper.addExceptionOrder(exceptionOrder);
            return row>0?"订单等待处理":"失败";
        }
        return null;
    }

    @Override
    @Transactional(isolation= Isolation.DEFAULT)
    public String handleExceptionOrder(String adminName, Integer orderId ,Integer yesNo) {
        if(yesNo!=2){
            //根据异常订单id查询订单状态
            Integer exctptionOrderstate = ordersMapper.selectExceptionOrderState(orderId);
            if (exctptionOrderstate == 2) {//换货
                ordersMapper.updateOrderExchange(orderId);//修改订单状态为待发货
                return ordersMapper.deleteExceptionOrder(orderId) > 0 ? "成功" : "失败";//删除异常订单
            } else {
                return ordersMapper.handleExceptionOrder(adminName, orderId) > 0 ? "成功" : "失败";
            }
        }else{
            return ordersMapper.handleExceptionOrder(adminName, orderId) > 0 ? "成功" : "失败";
        }

    }

    public Boolean orderPay(Integer orderId){
        return ordersMapper.orderPay(orderId)!=0;
    }

    @Override
    public List<UserOrder_Result> userSelectOrders(Integer userId, Integer page, Integer limit) {
        return ordersMapper.userSelectOrders((page-1)*limit,limit,userId);
    }

    @Override
    public Integer countUserOrder(Integer userId) {
        return ordersMapper.countUserOrder(userId);
    }


}
